<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of owlnote
 *
 * @author trung
 */
class Owl_Note extends Owl_Db {

    function Owl_Note() {
        $this->Owl_Db('note');
    }

    function get_all_notes() {
        $sticky =  $this->get_results('//note[sticky = 1]');
        $non_sticky = $this->get_results('//note[sticky = 0]');
        return array_merge(array_reverse((array)$sticky), array_reverse((array)$non_sticky));
    }

    function get_notes_for_rss() {
        return array_slice(array_reverse((array)$this->get_results('//note')), 0, get_option("content_per_page", 10));
    }

    function get_note($create_date) {
        if ( empty($create_date) )
            return false;
        return $this->get_row('/notes/note[create_date="'.$create_date.'"]');
    }

    function insert_notes($data) {
        $now = Owl_Date_Time::current_time('xml', true);
        $defaults = array(
            'content' => '',
            'create_date' => $now,
            'modify_date' => $now,
            'sticky' => '0'
        );
        $data = Owl_System_Helper::array_merge($data, $defaults);
        return $this->insert('/notes', 'note', $data);
    }

    function delete_notes($create_date) {
        if ( empty($create_date) )
            return false;
        return $this->delete('/notes/note[create_date="'.$create_date.'"]');
    }

    function update_notes($create_date, $data) {
        if ( empty($create_date) )
            return false;
        $old_note = $this->get_note($create_date);
        if ($old_note === false) {
            $this->last_error = new Owl_Error('503', _('Note is not exist'));
            return false;
        }
        $now = Owl_Date_Time::current_time('xml', true);
        $defaults = array(
            'content' => $old_note['content'],
            'create_date' => $create_date,
            'modify_date' => $now,
            'sticky' => $old_note['sticky']
        );
        $data = Owl_System_Helper::array_merge($data, $defaults);
        return $this->update('/notes/note[create_date="'.$create_date.'"]','note',$data);
    }

    function get_last_note() {
        return end($this->get_results("//note"));
    }

    function to_json($args = array()) {
        $page = 1;
        $admin = false;
        extract($args);

        $data = array();
        $notes = $this->get_all_notes();
        if ($notes === false) {
            $data["code"] = 0;
            $data["message"] = $this->get_error();
        }
        else {
        //Paging
            $total = count($notes);
            $page_boundary = Owl_Functions::get_pagination_boundary($page, $total);

            if ($page_boundary !== false) {
                $data["code"] = 1;
                $data["message"] = "Success";
                $data["total"] = ceil($total / get_option("content_per_page", 15));

                list($begin, $end) = $page_boundary;
                $data["hasTab"] = false;
                $data["hasHeader"] = false;
                $data["rows"] = array();

                //Fetch content
                for ($i = $begin; $i <= $end; $i++) {
                    $note = $notes[$i];
                    $row = array();
                    if ($note["sticky"]) {
                        $row["content"][] = "<div class=\"note-content sticky\">" .  Owl_Format::make_nice_textarea_content($note["content"]) . "</div>";
                    }
                    else {
                        $row["content"][] = "<div class=\"note-content\">" .  Owl_Format::make_nice_textarea_content($note["content"]) . "</div>";
                    }
                    if ($note["create_date"] == $note["modify_date"]) {
                        $row["content"][] = "<div class=\"note-detail\">" . sprintf(__('Posted by <span class="note-author">%s</span> at <span class="note-time">%s</span>'), Owl_Default_Content::get_site_author(), Owl_Date_Time::w3c_to_owl_date($note["create_date"])) . "</div>";
                    }
                    else {
                        $row["content"][] = "<div class=\"note-detail\">" . sprintf(__('Modified by <span class="note-author">%s</span> at <span class="note-time">%s</span>'), Owl_Default_Content::get_site_author(), Owl_Date_Time::w3c_to_owl_date($note["modify_date"])) . "</div>";
                    }
                    if ($args["admin"]) {
                        $row["form"][__("Edit")] = $this->build_form($note, $i);
                    }
                    $data["rows"][] = $row;
                }
            }
            else {
                $data["code"] = 0;
                $data["message"] = __("No data");
            }
            $data["controlText"] = Owl_Functions::get_control_text();
            return Owl_Functions::json_encode($data);
        }
    }

    function build_form($note, $pos) {
        $string = "<div class=\"form-container\">\n";
        $string .= "<form action=\"" . Owl_Link::ajax_url(false) . "note-ajax.php\" method=\"POST\" id=\"form-note-edit-$pos\">\n";
        $string .= Owl_Form::print_hidden(array(
            "name" => "create_date",
            "value" => $note["create_date"],
            "toString" => true
        ));
        $string .= Owl_Form::print_hidden(array(
            "name" => "action",
            "value" => "edit_note",
            "toString" => true
        ));
        $string .= "<div class=\"form-note-textarea-container\">\n";
        $string .= Owl_Form::print_textarea(array(
            "name" => "content",
            "class" => "form-textarea form-note",
            "rows" => 5,
            "value" => Owl_Format::esc_html($note["content"]),
            "toString" => true
        ));
        $string .= "</div>\n";
        $string .= "<div class=\"form-note-button-pane\">\n";
        $string .= "<div class=\"form-note-sticky\">\n";
        $string .= Owl_Form::print_label(array(
            "value" => __("Sticky"),
            "toString" => true
        ));
        $string .= Owl_Form::print_check_box(array(
            "name" => "sticky",
            "value" => ($note["sticky"] == 1) ? "on" : "",
            "toString" => true
        ));
        $string .= "</div>\n";
        $string .= "<div class=\"form-note-button-container\">\n";
        $string .= "<img src=\"" . Owl_Link::image_url(false) . "default/ajax-load.gif\" class=\"ajax-load\" alt=\"Ajax load\" />\n";
        $string .= "<input type=\"submit\" name=\"submit-edit-$pos\" value=\"" . __("Edit note") . "\" class=\"form-button edit-note\" title=\"form-note-edit-$pos\" />\n";
        $string .= "<input type=\"submit\" name=\"submit-delete-$pos\" value=\"" . __("Delete note") . "\" class=\"form-button delete-note\" title=\"form-note-edit-$pos\" />\n";
        $string .= "<input type=\"reset\" name=\"submit-cancel-$pos\" value=\"" . __("Cancel") . "\" class=\"form-button cancel-edit\" title=\"form-note-edit-$pos\" />\n";
        $string .= "</div>\n";
        $string .= "</div>\n";
        $string .= "<div style=\"clear:both;\"></div>\n";
        $string .= "<div class=\"ajax-feedback\">\n";
        $string .= "<div class=\"ajax-message\"></div>\n";
        $string .= "</div>\n";
        $string .= "</form>\n";
        $string .= "</div>\n";
        return $string;
    }

    function to_rss() {
        $rss_data = $this->get_notes_for_rss();
        echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        echo '<rss version="2.0">' . "\n";
        echo '<channel>' . "\n";
        echo '<title>' . Owl_Format::esc_html(get_option('site_name')) . ' - ' . __("Notes") . '</title>' . "\n";
        echo '<link><![CDATA[' . "http://" . $_SERVER["HTTP_HOST"] . Owl_Link::site_url(false) . ']]></link>' . "\n";
        echo '<description>' . sprintf(__("Notes from %s"), Owl_Format::esc_html(get_option('site_name'))) . '</description>' . "\n";
        if (!empty ($rss_data)) {
            foreach ($rss_data as $item) {
                echo '<item>'."\n";
                echo '<title><![CDATA[' . sprintf(__("Note at %s"), Owl_Format::esc_html(Owl_Date_Time::w3c_to_owl_date($item["create_date"]))) .']]></title>'."\n";
                echo '<link><![CDATA[' . "http://" . $_SERVER["HTTP_HOST"] . Owl_Link::site_url(false) . ']]></link>'."\n";
                echo '<description><![CDATA[' . Owl_Format::esc_html($item["content"]) . ']]></description>'."\n";
                echo '<pubDate><![CDATA[' . Owl_Date_Time::w3c_to_date($item["create_date"], DATE_RSS, false, false) . ']]></pubDate>'."\n";
                echo '</item>'."\n";
            }
        }
        echo '</channel>' . "\n";
        echo '</rss>';
    }

}

